package com.arch.dev.server.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.authentication.encoding.PasswordEncoder;

import com.arch.dev.client.vo.BudgetVO;

public class BudgetCalcUtil {
	public static String encryptPassword(String pwd) {
		PasswordEncoder encoder = new Md5PasswordEncoder();
		return encoder.encodePassword(pwd, "ABC123XYZ789");
	}

	public static File convertToExcel(File fileName, List<BudgetVO> budgetVOs)
			throws IOException {

		// create a new file
		FileOutputStream out = new FileOutputStream(fileName);
		// create a new workbook
		Workbook wb = new HSSFWorkbook();
		// create a new sheet
		Sheet s = wb.createSheet();
		// declare a row object reference
		Row r = null;
		// declare a cell object reference
		Cell c = null;
		// create 3 cell styles
		CellStyle cs = wb.createCellStyle();
		CellStyle cs2 = wb.createCellStyle();
		CellStyle cs3 = wb.createCellStyle();
		DataFormat df = wb.createDataFormat();

		cs3.setDataFormat(df.getFormat("dd/mm/yy"));

		// set the cell format
		cs.setDataFormat(df.getFormat("#,##0.0"));

		// set the cell format to text see DataFormat for a full list
		cs2.setDataFormat(HSSFDataFormat.getBuiltinFormat("text"));

		wb.setSheetName(0, "HSSF Test");

		r = s.createRow(0);
		c = r.createCell(0);
		c.setCellValue("Description");
		c.setCellStyle(cs2);

		c = r.createCell(1);
		c.setCellValue("Category");
		c.setCellStyle(cs2);

		c = r.createCell(2);
		c.setCellValue("Price");
		c.setCellStyle(cs2);

		c = r.createCell(3);
		c.setCellValue("Date");
		c.setCellStyle(cs2);

		int rownum = 1;
		for (BudgetVO budgetVO : budgetVOs) {
			// create a row
			r = s.createRow(rownum);

			c = r.createCell(0);
			c.setCellValue(budgetVO.getTitle());
			c.setCellStyle(cs2);

			c = r.createCell(1);
			c.setCellValue(budgetVO.getCatagoryVO().getName());
			c.setCellStyle(cs2);

			c = r.createCell(2);
			c.setCellValue(budgetVO.getCost().doubleValue());
			c.setCellStyle(cs);

			c = r.createCell(3);
			c.setCellValue(budgetVO.getDate());
			c.setCellStyle(cs3);

			rownum++;
		}

		wb.write(out);
		out.close();

		return fileName;
	}

}
